<template>
  <div class="app-container">
    <el-row :gutter="12">
      <el-col :span="8">
        <div class="panel-info">
          <div class="panel-title">流程名称</div>
          <div class="panel-body">
            <div class="btn-group">
              <el-input style="width:220px;" placeholder="输入流程名称/编号查询" prefix-icon="el-icon-search"
                v-model="query.queryString">
              </el-input>
              <el-button style="float:right" size="small" type="primary" v-permission="'workflow.add'"
                @click="createItem" title="添加流程">
                添加目录/流程
              </el-button>
            </div>
            <div class="pt-25">
              <el-tree draggable v-loading="treeLoading" :allow-drop="treeAllowDrop" style="font-size:13px"
                :data="workflowList" @node-drag-end="treeHandleDragEnd" :current-node-key.sync="data.id" ref="treeRef"
                class="filter-tree" :default-expand-all="true" highlight-current :props="defaultProps" accordion
                node-key="id" @node-click="nodeClick">
                <div slot-scope="{ data }" class="flex flex-col-between flex-center" style="width:100%">
                  <div>
                    <span v-if="data.children.length<=0"></span>
                    <i class="el-icon-folder" style="vertical-align: top" v-show="data.type==0"></i><i
                      class="el-icon-document" style="vertical-align: top" v-show="data.type==1"></i><span
                      :title="data.label" class="span-ellipsis">&nbsp;

                      <span v-if="data.is_enable==0" style="color:#F56C6C">{{data.label}}</span>
                      <span v-else>{{data.label}}</span></span>
                  </div>
                  <div>
                    <!-- <a href="#" class="t-14 text-hover text-blue" v-if="data.type==1" title="编辑"
                      @click.prevent.stop="nodeClick(data,false)">
                      <i class="fa fa-edit"></i>
                    </a> -->
                    <a href="#" class="t-14 text-hover text-red" title="删除" @click.prevent.stop="deleteItem(data)">
                      <i class="fa fa-trash"></i>
                    </a>
                  </div>
                </div>
              </el-tree>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="16" v-if="rightShow">
        <div class="panel-info">
          <transition name="fade" mode="out-in">
            <div v-if=" bindType" key="out" style="height:100%">
              <div class="panel-title">{{'流程设计--版本:'+data.version}}</div>
              <div class="panel-body" style="padding:0;position:relative">
                <div class="fr p-20 save-post">
                  <div class="flex flex-center">
                    <el-button type="warning" @click="nodeClick(data,true)">取消</el-button>
                    <!-- <i class="fa fa-refresh mr-20" style="	cursor: pointer;"
                      @click.self="$refs.scworkflow.refresh()"></i> -->
                    <el-button type="primary" @click="updateJsonData" :loading="saveLoading">保存</el-button>
                  </div>
                </div>
                <sc-workflow :modelValue.sync="data.json_data" ref="scworkflow">
                </sc-workflow>
              </div>
            </div>
            <div v-if="!bindType" key="in">
              <div class="panel-title">基础数据--{{workFlowSetName}}<span></span></div>
              <div class="panel-body p-r">
                <div class="fl p-20 cancel">
                  <!-- <div class="flex flex-center">
                    <el-button type="warning" v-if="data.id" @click="nodeClick(data)" :loading="saveLoading">取消
                    </el-button>
                  </div> -->
                </div>
                <div class="fr p-20 save-post">
                  <div class="flex flex-center">
                    <el-button type="primary" @click="submit" :loading="saveLoading">保存</el-button>
                  </div>
                </div>
                <div style="min-height:20vh;" class="pt-80">
                  <el-form label-width="100px">
                    <el-row>
                      <el-form-item label="" v-if="data.id && data.type==1">
                        <el-button type="success" @click.native="nodeClick(data,false)" v-permission="'workflow.edit'"
                          :loading="submitLoading" plain>
                          流程设计
                        </el-button>
                        <el-dropdown class="ml-5" @command="changeVersion" v-permission="'workflow.edit'">
                          <el-button type="info" plain>
                            查看历史版本<i class="el-icon-arrow-down el-icon--right"></i>
                          </el-button>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="it in data.version_list" :key="it.id" :command="it.id">
                              {{it.version}}
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                        <el-button class="ml-5" type="warning" v-permission="'workflow.edit'" plain
                          @click="addNewVersion">
                          流程升版
                        </el-button>
                      </el-form-item>
                      <el-col :span="12">
                        <el-form-item>
                          <span slot="label">
                            <span class="text-red">*</span>
                            <span>类型</span>
                          </span>
                          <el-select :disabled="!!data.id" v-model="data.type" @change="directoryChange"
                            style="width: 100%">
                            <el-option label="目录" :value="0">
                            </el-option>
                            <el-option label="流程" :value="1">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item>
                          <span slot="label">
                            <span class="text-red">*</span>
                            <span>名称</span>
                          </span>
                          <el-input :disabled="data.id && data.type==1" v-model="data.name"></el-input>
                        </el-form-item>
                      </el-col>
                      <span v-if="data.type==1">
                        <el-col :span="12">
                          <el-form-item>
                            <span slot="label">
                              <span class="text-red">*</span>
                              <span>版本</span>
                            </span>
                            <el-input v-model="data.version" placeholder="请输入大于0的数字"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item>
                            <span slot="label">
                              <span class="text-red">*</span>
                              <span>是否启用</span>
                            </span>
                            <el-switch v-model="data.is_enable" :active-value="1" :inactive-value="0">
                            </el-switch>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item>
                            <span slot="label">
                              <span class="text-red">*</span>
                              <span>路由页面</span>
                            </span>
                            <el-select v-model="data.form_name" filterable style="width: 100%">
                              <el-option v-for="o in menuOptions" :label="o.menu_name" :value="o.path" :key="o.id">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </span>
                    </el-row>
                  </el-form>
                  <!-- <z-form :formProps="{labelWidth:'100px'}" :fields="fields" :data="data">
                  </z-form> -->
                </div>
              </div>
            </div>
          </transition>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="流程升版" width="50%" :close-on-click-modal="false" :visible.sync="addVersinModalVisible">
      <div style="padding-right: 80px;">
        <el-form :model="newVersionData" label-width="100px">
          <el-form-item label="流程名称">
            <el-input v-model="newVersionData.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="原版本">
            <el-input v-model="newVersionData.version" disabled></el-input>
          </el-form-item>
          <el-form-item label="新版本">
            <el-input v-model="newVersionData.newVersion"></el-input>
          </el-form-item>
          <div class="text-right dialog-footer">
            <el-button @click="addVersinModalVisible = false">取消</el-button>
            <el-button type="primary" @click.native="addNewVersionSubmit()" :loading="submitLoading">
              确认
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import scWorkflow from '@/views/components/scWorkflow'
import commonMixin from '@/views/_common/mixin.js'
export default {
  name: 'workflow',
  mixins: [commonMixin],
  components: {
    scWorkflow,
  },
  data() {
    return {
      api: this.$api.workflow,
      apiCreate: this.$api.workflow + 'Modify',
      menuOptions: [],
      name: '工作流',
      isDirectory: true,
      workflowList: [],
      workFlowSetName: '',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      query: {
        page: 1,
        size: 999,
        queryString: '',
      },
      nodeConfig: {
        nodeName: '发起人',
        type: 0,
        nodeRoleList: [],
      },
      bindType: true,
      treeLoading: false,
      saveLoading: false,
      editFormVisible: false,
      data: { is_enable: 1 },
      rightShow: false,
      addVersinModalVisible: false,
      newVersionData: {},
    }
  },
  watch: {
    'query.queryString': {
      handler() {
        this.getList()
      },
    },
  },
  created() {
    this.$request(this.$api.menuOptions, { client: 'WEB' }).then((r) => {
      this.menuOptions = r
    })
    this.getList()
  },
  mounted() {},
  methods: {
    treeHandleDragEnd(beforeNode, afterNode, type, event) {
      this.$request(
        this.api + 'UpdateSort',
        { before_id: beforeNode.data.id, after_id: afterNode.data.id, type },
        'post',
      ).then((r) => {})
    },
    treeAllowDrop(draggingNode, dropNode, type) {
      if (dropNode.data.type == 1 && type == 'inner') {
        return false
      }
      return true
    },
    directoryChange() {
      if (this.data.type == 0) {
        this.data.is_enable = ''
        this.data.version = ''
        this.data.form_name = ''
      } else {
        this.data.is_enable = 1
      }
    },
    createItem() {
      this.bindType = false
      this.rightShow = true
      if (this.data && this.data.type == 1) {
        this.$message.error('流程不可以创建下级，请选中目录')
        return
      }
      this.workFlowSetName = '目录/流程创建'
      //取消行高亮
      //this.$refs.treeRef.setCurrentKey(null)
      let data = _.cloneDeep(this.data)
      this.data = { parent_id: data.id ? data.id : '0', type: 0, is_enable: 1 }
    },
    nodeClick(data, v) {
      this.$request(this.api + 'getbyid', { id: data.id }).then((r) => {
        if (data.type == 1) r.json_data = r.json_data ? JSON.parse(r.json_data) : _.cloneDeep(this.nodeConfig)
        this.data = r
        this.workFlowSetName = this.data.type == 0 ? '目录编辑' : '流程编辑' + '--版本:' + this.data.version
        this.$nextTick(() => {
          this.$refs['treeRef'].setCurrentKey(this.data.id)
        })

        if (v) {
          this.bindType = false
        } else {
          this.bindType = true
        }
        this.rightShow = true
      })
    },
    queryFormData(data) {
      let tmp = _.cloneDeep(data)
      tmp.workflow_id = tmp.id
      tmp.json_data = JSON.stringify(tmp.json_data)
      for (let key in tmp) {
        if (key != 'workflow_id' && key != 'json_data') delete tmp[key]
      }
      return tmp
    },
    formatBeforeSave(data) {
      let tmp = _.cloneDeep(data)
      tmp.version = parseFloat(tmp.version)
      return tmp
    },
    getList(callback) {
      this.treeLoading = true
      this.$request(this.api + 'getlist', this.query).then((r) => {
        this.workflowList = r
        if (callback) callback(r)
        this.treeLoading = false
      })
    },
    submit() {
      let url = this.apiCreate
      let data = _.cloneDeep(this.data)
      data.json_data = data.json_data ? JSON.stringify(data.json_data) : ''
      this.submitLoading = true
      this.$request(url, data, 'post')
        .then((r) => {
          this.data = r
          this.$message.success('保存成功')
          this.getList((r) => {
            this.$nextTick(() => {
              this.$refs['treeRef'].setCurrentKey(this.data.id)
            })
          })
          //显示要高亮的代码
          this.nodeClick({ id: this.data.id }, true)
        })
        .finally(() => {
          this.submitLoading = false
        })
    },

    jsonParseOrStringfy(v = true, data) {
      return new Promise((resolve, reject) => {
        if (v) {
          resolve(JSON.parse(data))
        } else {
          resolve(JSON.stringify(data))
        }
      })
    },

    updateJsonData() {
      this.saveLoading = true
      this.$request(this.api + 'saveitem', this.queryFormData(this.data), 'post')
        .then((r) => {
          this.data.json_data = _.cloneDeep(r.orgin_data)
          this.saveLoading = false
          this.$message.success('保存成功')
        })
        .catch((e) => {
          this.saveLoading = false
        })
    },
    changeVersion(v) {
      this.nodeClick({ id: v }, true)
    },
    addNewVersion() {
      this.newVersionData = _.cloneDeep(this.data)
      this.addVersinModalVisible = true
    },
    addNewVersionSubmit() {
      let data = {
        id: this.data.id,
        version: this.newVersionData.newVersion,
      }
      this.$request(this.api + 'UpdateWorkflowVersion', data, 'post').then((r) => {
        this.$message.success('操作成功')
        this.addVersinModalVisible = false
        this.getList(() => {
          this.nodeClick({ id: r }, true)
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.cancel {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 999;
}

.save-post {
  position: absolute;
  right: 0;
  top: 0;
  z-index: 999;
}

::v-deep .el-tree-node__content {
  width: 100%;
}

.text-hover {
  margin-right: 10px;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.panel-info:last-of-type {
  height: calc(100vh - 120px);
  overflow: hidden;

  .panel-body {
    height: 100% !important;
  }
}
</style>
